import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:recipe/module/api.dart';
import 'package:recipe/module/toast.dart';

import 'module/globalColor.dart';

class Info extends StatefulWidget {
  Info({Key key, @required this.infoId}) : super(key: key);
  String infoId = '';
  @override
  _InfoState createState() => _InfoState();
}

class _InfoState extends State<Info> {
  String likeText = '';
  Map infoData = {
    "foodTitle": '',
    "foodUrl": '',
    "foodStuff": {"m": [], "f": [], "t": []},
    "foodMethod": [
      {"iSrc": '', "iSub": ''}
    ]
  };
  @override
  void initState() {
    getInfo().then((res) {
      setState(() => {infoData = res, likeText = res["isLike"] ? "已收藏" : "收藏"});
    });
    super.initState();
  }

  getInfo() async {
    String url = "detail?id=${widget.infoId}";
    try {
      var response = await HttpRequest.request(url, method: HttpRequest.GET);
      return response["data"];
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            "做法详情",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 15,
            ),
          ),
        ),
        body: SingleChildScrollView(
            child: Container(
          padding: EdgeInsets.only(left: 15, right: 15),
          child: Column(
            children: [
              renderMainImg(infoData),
              ...renderB(infoData["foodStuff"]),
              ...renderM(infoData["foodMethod"])
            ],
          ),
        )));
  }

  // renderMainImg

  renderMainImg(item) {
    return Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(top: 15, bottom: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: Text(item['foodTitle'],
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                )),
          ),
          SizedBox(height: 15),
          Container(
            width: MediaQuery.of(context).size.width,
            height: 200,
            child: ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(5)),
              child: FadeInImage.assetNetwork(
                  placeholder: 'assets/images/cover.jpg',
                  fadeInDuration: const Duration(milliseconds: 500),
                  image: item['foodUrl'],
                  fit: BoxFit.cover
                  // image:s
                  ),
            ),
          ),
          SizedBox(height: 15),
          Container(
            child: Center(
                child: new MaterialButton(
              // color: GlobalColor.themeColor,
              color: GlobalColor.themeColor,
              textColor: Colors.white,
              child: new Text(likeText),
              shape: RoundedRectangleBorder(
                  side: BorderSide.none,
                  borderRadius: BorderRadius.all(Radius.circular(5))),

              onPressed: () {
                like().then((res) {
                  setState(() {
                    likeText = "已收藏";
                  });
                  Toast.toast(context, msg: res["msg"]);
                });
              },
            )),
          )
        ],
      ),
    );
  }

  // 收藏接口

  like() async {
    String url = "like?id=${widget.infoId}";
    try {
      var response = await HttpRequest.request(url, method: HttpRequest.GET);
      return response;
    } catch (e) {
      print(e);
    }
  }

  // 配料
  List<Widget> renderB(infoData) {
    List<Widget> list = [
      SizedBox(height: 10),
      Row(
        children: [
          SizedBox(width: 10),
          Text(
            "配料：",
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.w700,
            ),
          ),
        ],
      ),
      SizedBox(height: 10),
    ];
    List arr = [...infoData["m"], ...infoData["f"], ...infoData["t"]];
    List.generate(arr.length, (index) {
      final item = arr[index];
      list.add(Container(
          width: MediaQuery.of(context).size.width,
          padding: EdgeInsets.only(left: 15, right: 15, top: 10, bottom: 10),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
          child: Row(children: [
            Expanded(
                child: Text(item["name"],
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ))),
            Container(
                width: 50,
                child: Text(item["sub"],
                    style: TextStyle(
                      color: Colors.black54,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    )))
          ])));
    });
    return list;
  }

  // 做法步骤
  List<Widget> renderM(infoData) {
    List<Widget> list = [
      SizedBox(height: 10),
      Row(
        children: [
          SizedBox(width: 10),
          Text(
            "步骤：",
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.w700,
            ),
          ),
        ],
      ),
      SizedBox(height: 10),
    ];
    List.generate(
        infoData.length,
        (index) => {
              list.add(Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                    // color: Global.cardBackgroundColor,
                    ),
                child: Column(
                  children: [
                    FadeInImage.assetNetwork(
                        placeholder: 'assets/images/cover.jpg',
                        fadeInDuration: const Duration(milliseconds: 500),
                        image: infoData[index]["iSrc"]),
                    SizedBox(height: 10),
                    Text(infoData[index]["iSub"])
                  ],
                ),
              ))
            });
    return list;
  }
}
